<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="98px">
      <el-form-item label="分机号名称" prop="extensionName">
        <el-input v-model="queryParams.extensionName" placeholder="请输入分机号名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>

      <el-form-item label="类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择类型" clearable style="width: 240px">
          <el-option v-for="dict in queryParams.sys_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:number:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:number:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:number:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['system:number:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="numberList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键id" align="center" prop="extensionId" />
      <el-table-column label="分机号名称" align="center" prop="extensionName" />
      <el-table-column label="号码" align="center" prop="number" />
      <el-table-column label="绑定人员" align="center" prop="userName" />
      <el-table-column label="绑定组织 " align="center" prop="deptName" />

      <el-table-column label="分机号类型" align="center" prop="type" :formatter="(row) => {
        const typeMap = {
          '0': '内线',
          '1': '前台',
          '2': '客房'
        };
        return typeMap[row.type] || row.type;
      }" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:number:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:number:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改分机号对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="numberRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="分机号名称" prop="extensionName">
          <el-input v-model="form.extensionName" placeholder="请输入分机号名称" />
        </el-form-item>
        <el-form-item label="分机号" prop="number">
          <el-input v-model="form.number" placeholder="请输入分机号" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="请选择类型" clearable style="width: 240px">
            <el-option v-for="dict in queryParams.sys_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="绑定人员或组织" prop="responsibleBy">
          <el-tree-select v-model="form.responsibleBy" :data="responseOptions" :render-after-expand="false"
            show-checkbox :props="treeProps" check-strictly check-on-click-node node-key='id' filterable
            style="width: 100%" placeholder="绑定人员或组织" @check="handleCheckChange"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Number">addNumber
import { listNumber, getNumber, delNumber, addNumber, updateNumber } from "@/api/system/number";
import useUserStore from "@/store/modules/user";
import { deptUserTree } from "@/api/system/role";
import { ref, onMounted } from 'vue';

const { proxy } = getCurrentInstance();

const numberList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const treeProps = {
  value: 'id',
  label: 'label',
  children: 'children',
  // 可选：禁用用户节点选择
  // disabled: (data) => !data.isUser
};
const responseOptions = ref([])


const data = reactive({
  form: {
    responsibleById:'',
    responsibleByType:'',
    userId: '',    // 存储用户ID
    deptId: ''
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    extensionName: null,
    number: null,
    userId: null,
    deptId: null,
    responsibleById:null,
    type: null,
    sys_type: [
      { value: '0', label: '内线' },
      { value: '1', label: '前台' },
      { value: '2', label: '客房' }
    ],

  },


  rules: {
    extensionName: [
      { required: true, message: "分机号名称不能为空", trigger: ['change', 'blur'] }
    ],
    number: [
      { required: true, message: "分机号不能为空", trigger: "blur" },
      { pattern: /^\d+$/, message: "只能输入数字", trigger: "blur" },
    ],
    type: [
      // { required: true, message: '类型不能为空', trigger: ['change','blur'] }
    ],
    responsibleBy: [
    { required: true, message: '请选择人员或组织', trigger: 'change' },
  ],
    userId: [
    ],
    deptId: [
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);
onMounted(async () => {
  
  try {
    await useUserStore().getInfo();
    const res = await deptUserTree({});
    if (res.data) {
      responseOptions.value =[transformDeptTree(res.data, true)];
    }
  } catch (error) {
    console.error("加载部门树失败:", error);
  }
});

function transformDeptTree(deptNode) {
  if (!deptNode) return { id: '', label: '', children: [] };
  
  // 使用深拷贝创建全新对象
  const newNode = {
    id: `dept_${deptNode.deptId}`,
    deptId: deptNode.deptId,
    label: deptNode.deptName,
    isDept: true, // 添加部门标识
    type: 'dept',  // 明确类型标识
    children: []
  };

  // 处理用户列表（确保每个节点都是新对象）
  if (deptNode.userList?.length) {
    newNode.children.push(
      ...deptNode.userList.map(user => ({
        id: `user_${user.userId}`,
        userId: user.userId,
        label: `${user.nickName} (${user.userName})`,
        isUser: true,
        type: 'user',  // 明确类型标识
        children: []  // 必须包含空数组
      }))
    );
  }

  // 递归处理子部门（确保每次递归都返回新对象）
  if (deptNode.children?.length) {
    newNode.children.push(
      ...deptNode.children.map(child => transformDeptTree(child))
    );
  }
  return newNode;
}

function handleCheckChange(data, checked) {
      // 清除之前的选择
      this.form.responsibleByType = '';
      this.selectedNode = null;

      // 如果当前节点被选中
      if (checked) {
        if (data.isUser) {
          this.form.responsibleById = data.id.split('_')[1]; // 提取 userId
          this.form.responsibleByType = 'user';
        } else {
             this.form.responsibleById = data.id.split('_')[1]; // 提取 deptId
          this.form.responsibleByType = 'dept';
        }
        this.selectedNode = data; // 更新选中的节点（可选，用于显示或其他逻辑）
        // 更新选中状态
       this.selectedNodeId = checkedNode.id;
      }
    }
  


/** 查询分机号列表 */
function getList() {
  loading.value = true;
  listNumber(queryParams.value).then(response => {
    numberList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    extensionId: null,
    extensionName: null,
    number: null,
    userId: null,
    deptId: null,
    type: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    type:null,
    extensionName: null,
    number: null,
    // 其他参数...
    sys_type: []
  });
  proxy.resetForm("numberRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.extensionId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加分机号";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _extensionId = row.extensionId || ids.value
  getNumber(_extensionId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改分机号";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["numberRef"].validate(valid => {
    if (valid) {
      if (form.value.extensionId != null) {
        updateNumber(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addNumber(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          proxy.resetForm("queryRef");
          handleQuery();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _extensionIds = row.extensionId || ids.value;
  proxy.$modal.confirm('是否确认删除分机号编号为"' + _extensionIds + '"的数据项？').then(function () {
    return delNumber(_extensionIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/number/export', {
    ...queryParams.value
  }, `number_${new Date().getTime()}.xlsx`)
}



getList();
</script>
